package com.xingxuecn.demos.controller;

import com.xingxuecn.demos.common.Constant;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 上传下载
 * @author Kris at 2018/9/28 11:38
 */
@RestController
@RequestMapping("file")
public class FileUploadController {
    static Logger logger = Logger.getLogger(FileUploadController.class);

    static FastDateFormat fdf_fileName = FastDateFormat.getInstance("yyyyMMddHHmmss");
    static FastDateFormat fdf_filePathName = FastDateFormat.getInstance("yyyyMMdd");

    /**
     * 上传入口
     * @return
     */
    @GetMapping({"index", "", "/"})
    public ModelAndView index() {
        return new ModelAndView("common/upload");
    }

    /**
     * 上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public ResponseEntity<String> upload(@RequestParam MultipartFile file) throws IOException {
        Date current = new Date();
        String pristineName = file.getOriginalFilename();
        String fileName = new StringBuffer()
                .append(fdf_fileName.format(current).replaceAll(" ", ""))
                .append('_')
                .append(pristineName)
                .toString();

        String currentDateStr = fdf_filePathName.format(current);
        String filePathName = currentDateStr + "/" + fileName;
        File fileDest = new File(Constant.FILE_UPLOAD_ROOT_PATH +filePathName);
        if(!fileDest.exists()){
            fileDest.mkdirs();
        }
        file.transferTo(fileDest);
        logger.info("目标目录："+fileDest.getPath());
        return ResponseEntity.ok(filePathName);
    }

    /**
     * 下载
     * @param filePath
     * @return
     * @throws IOException
     */
    @GetMapping("download")
    public ResponseEntity<File> download(@RequestParam String filePath) throws IOException {
        filePath = Constant.FILE_UPLOAD_ROOT_PATH + filePath;
        File f = new File(filePath);
        InputStream in;
        try {
            in = new FileInputStream(f);
            byte[] bytes = new byte[in.available()];
            in.read(bytes);
            HttpHeaders headers = new HttpHeaders();
            String fileName = new String(f.getName().getBytes("gbk"),"iso8859-1");
            headers.add("Content-Disposition", "attachment;filename=" + fileName);
            in.close();
            return new ResponseEntity(bytes, headers, HttpStatus.OK);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
